///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.data.handlers.xml {
	import flash.events.EventDispatcher;
	
	import sugarcookie.data.handlers.IDataHandler;
	import sugarcookie.error.ApplicationError;
	import sugarcookie.events.DataEvent;
	import sugarcookie.events.GenericEvent;
	import sugarcookie.file.DataLoader;
	
	/**
	 * Composites the XMLLoader class and provides an API that works with the sugarcookie XML Schema.
	 */
	public class XMLHandler extends EventDispatcher implements IDataHandler {
		private var _isAutoLoad:Boolean = false;
		private var _xmlURI:String;
		private var _xmlLoader:DataLoader;
		private var _xml:XML;
		private var _id:String = "XML";
		
		public function XMLHandler(uri:String) {
			super(this);
			_xmlURI = uri;
		}
		
		public function get autoLoad():Boolean { return _isAutoLoad; }
		public function set autoLoad(value:Boolean):void { _isAutoLoad = value; }
		
		public function get id():String { return _id; }
		public function set id(value:String):void { _id = value; }
		
		public function kill():void {
			_xmlLoader = null;
		}
		
		public function init():void {
			_xmlLoader = new DataLoader(_xmlURI);
			_xmlLoader.addEventListener(DataLoader.ERROR,onError,false,0,true);
			_xmlLoader.addEventListener(DataLoader.STATUS,onStatus,false,0,true);
			_xmlLoader.addEventListener(DataLoader.COMPLETE,onComplete,false,0,true);
			_xmlLoader.load();
		}
		
		public function get xml():XML {
			return _xml;
		}
		
		private function onError(evt:GenericEvent):void {
			dispatchEvent(new DataEvent(DataEvent.ON_DATA_CHANNEL_ERROR,false,false,_id,true,evt.data));
		}
		
		private function onStatus(evt:GenericEvent):void {
			//could dispatch loading info here
		}
		
		private function onComplete(evt:GenericEvent):void {
			_xml = new XML(_xmlLoader.data as String);
			
			if (_isAutoLoad) dispatchEvent(new DataEvent(DataEvent.ON_AUTO_LOAD_COMPLETE,false,false,_id,true));
			else dispatchEvent(new DataEvent(DataEvent.ON_DATA_CHANNEL_RETURN,false,false,_id,true));
		}
	}
}